package com.hqyj.am.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.am.dao.UserMapper;
import com.hqyj.am.pojo.ResultVo;
import com.hqyj.am.pojo.User;
import com.hqyj.am.service.LoginService;
import com.hqyj.am.util.MDFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: chenglongfei
 * @date: 2022/8/17
 * @Description LoginServiceImpl
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    //短信登录
    @Override
    public ResultVo smsLogin(User user) {
        ResultVo rv = new ResultVo();
        //判断缓存中是否存在验证码的键名
        Object obj =redisTemplate.opsForValue().get("code:"+user.getPhone());
        //因为时间超时，验证码失效
        if(obj==null){
            rv.setInfo("验证码超过1分钟，失效了");
        }else{
            if(obj.equals(user.getCode())){
                rv.setInfo("登录成功");
                rv.setSuccess(true);
            }else{
                rv.setInfo("验证码输入不正确");
            }
        }
        return rv;
    }


    //用户名登录
//    @Override
//    public ResultVo userNameLogin(User user) {
//        ResultVo rv=new ResultVo();
//        String s= user.getUserName();
//        String s1= user.getUserPwd();
//        if (s.equals("admin") && s1.equals("123")) {
//            rv.setInfo("登录成功！");
//            rv.setSuccess(true);
//        }else {
//            rv.setInfo("登陆失败");
//        }
//        return  rv;
//    }

    @Override
    public ResultVo userLogin(User user) {
        ResultVo rv = new ResultVo();

        if(user.getUserName()==null){
            rv.setInfo("用户名为空，请重新输入！");
            return rv;
        }
        if(user.getUserPwd()==null){
            rv.setInfo("密码为空，请重新输入！");
            return rv;
        }

        MDFive mdFive = new MDFive();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_name", user.getUserName());
        User user1 = userMapper.selectOne(qw);
        user.setUserPwd(mdFive.encrypt(user.getUserPwd(),user1.getSalt()));
        System.out.println("user:"+user);
        System.out.println("user1:"+user1);
        if(user1==null){
            rv.setInfo("用户名输入错误，请重新输入！");
        }else if(!user1.getUserPwd().equals(user.getUserPwd())){
            rv.setInfo("密码输入错误，请重新输入！");
        }else {
            rv.setSuccess(true);
            rv.setData(user1);
            rv.setInfo("登陆成功");
        }
        return rv;
    }
}
